# coding:utf-8
# 作业1：测试和https请求
"""
1.python3 中,bytes和str相互转换
str.encode('utf-8')
bytes.decode('utf-8')
"""

import socket
import ssl


# 以下是request
def protocol_of_url(url):
    '''
    返回代表协议的字符串,'http'或者’https'
    :param url:
    :return:
    '''
    pass


def host_url(url):
    '''
    返回代表主机的字符串，比如'g.cn'
    :param url:
    :return:
    '''
    pass


def port_url(url):
    '''
    返回代表端口的字符串，比如'80'或者‘3000’
    80是默认端口
    :param url:
    :return:
    '''
    pass


def path_url(url):
    '''
    返回代表路径的字符串,比如'/'或者'/search'
    没有给路径的,默认使用/
    :param url:
    :return:
    '''
    pass


def parsed_url(url):
    """
    url是字符串，可能的形式如下：
    ‘g.cn'
    'g.cn/'
    'g.cn:3000'
    'g.cn:3000/search'
    'http://g.cn'
    'http://g.cn/'
    返回一个turple,形如（protocal host port path)
    :param url:
    :return:
    """
    # 检查协议
    protocol = 'http'
    if url[:7] == 'http://':
        u = url.split('://')[1]
    elif url[:8] == 'https://':
        protocol = 'https'
        u = url.split('://')[1]
    else:
        u = url

    # 检查默认 path
    i = u.find('/')
    if i == -1:
        host = u
        path = '/'
    else:
        host = u[:i]
        path = u[i:]
    # 检查端口
    port_dict = {
        'http': 80,
        'https': 443,
    }
    port = port_dict[protocol]
    if host.find(':') != -1:
        h = host.split(':')
        host = h[0]
        port = int(h[1])
    return protocol, host, port, path


# 简略版
# def get(url):
#     """
#     client.py中的方法使用socket连接服务器
#     获取服务器的数据并返回,
#     返回的数据类型为bytes
#     :param url:
#     :return:
#     """
#
#     import socket
#
#     s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#     host = url
#     # host = 'baidu.com'
#     port = 8080
#
#     s.connect((host, port))
#     ip, port = s.getsockname()
#     print('本机 ip 和 port {} {}'.format(ip, port))
#
#     http_request = 'GET / HTTP/1.1\r\nhost:{}\r\n'.format(host)
#     request = http_request.encode('utf-8')
#     print('请求', request)
#     s.send(request)
#
#     response = s.recv(1023)
#     print('响应', response)
#     print('响应的str格式', response.decode('utf-8'))
#     return response


# 以下是response

def socket_by_protocol(protocol):
    """
    返回一个socket实例
    """

    if protocol == 'http':
        s = socket.socket()
    else:
        s = ssl.wrap_socket(socket.socket())
    return s


def response_by_socket(s):
    """
    参数是一个socket实例，
    返回这个socket读取的所有数据
    """
    response = b''
    buffer_size = 1024
    while True:
        r = s.recv(buffer_size)
        if len(r) == 0:
            break
        response += r
    return response


def parsed_response(r):
    """
    把response 解析出 状态码 headers body 返回
    状态码是int
    herders是dict
    body是str
    """
    header, body = r.split('\r\n\r\n', 1)
    h = header.split('\r\n')
    status_code = h[0].split()[1]
    status_code = int(status_code)

    headers = {}
    for line in h[1:]:
        k, v = line.split(': ')
        headers[k] = v
    return status_code, headers, body


# 复杂的逻辑全部封装成函数
def get(url):
    """
    用Get 请求 url并返回请求
    """
    protocol, host, port, path = parsed_url(url)
    s = socket_by_protocol(protocol)
    s.connect((host, port))

    request = 'GET {} HTTP/1.1\r\nhost: {}\r\nConnection: close\r\n\r\n'.format(path, host)
    encoding = 'utf-8'
    s.send(request.encode(encoding))

    response = response_by_socket(s)
    r = response.decode(encoding)

    status_code, headers, body = parsed_response(r)
    if status_code == 301:
        url = headers['Location']
        return get(url)
    return status_code, headers, body


def main():
    url = 'http://movie.douban.com/top250'
    status_code, headers, body = get(url)
    print(status_code, headers, body)


# if __name__ == '__main__':
#     main()

# assert是一个语句,名字叫断言
# 如果断言成功,通过测试,否则测试失败，中断程序报错
def test_parsed_url():
    """
    parsed_url:很容易出错，所以我们需要写测试函数来检测
    :return:
    """
    http = 'http'
    https = 'https'
    host = 'baidu.com'
    path = '/'
    test_items = [
        ('http://baidu.com', (http, host, 80, path)),
        ('http://baidu.com/', (http, host, 80, path)),
        ('http://baidu.com:80', (http, host, 80, path)),
        ('http://baidu.com:80/', (http, host, 80, path)),
        ('https://baidu.com', (https, host, 443, path)),
    ]
    for t in test_items:
        url, expected = t
        u = parsed_url(url)
        e = "parse_url ERROR,({}) ({}) ({})".format(url, u, expected)
        assert u == expected, e


def test_parsed_response():
    """
    测试是否正常响应
    """
    # NOTE 行末的\表示连接多行字符串
    response = 'HTTP/1.1 301 Moved Permanently\r\n' \
               'Content-Type: text/html\r\n' \
               'Location: https://movie.douban.com/top250\r\n' \
               'Content-Length: 178 \r\n\r\n' \
               'test body'
    status_code, header, body = parsed_response(response)
    assert status_code == 301
    assert len(list(header.keys())) == 3
    assert body == 'test body'


def test_get():
    """
    检测是否能正确处理http和https
    :return:
    """
    urls = [
        'http://movie.douban.com/top250',
        'https://movie.douban.com/top250',
    ]
    for u in urls:
        get(u)


def test():
    """
    用于测试的主函数
    """
    test_parsed_url()
    test_get()
    test_parsed_response()
    pass


if __name__ == '__main__':
    test()
    main()
